package com.ksd1.notes;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ksd1.notes.db.NoteDB;

import java.util.List;

/**
 * 显示todo列表的适配器
 */
public class TodoAdapter extends RecyclerView.Adapter<TodoAdapter.ViewHolder>{
    private Context mContext;

    private List<NoteDB.Todo> mtodoList;
//    private boolean flag = false;//系统维护更新标志


    public TodoAdapter(List<NoteDB.Todo> todoList){
        mtodoList = todoList;
    }//浅拷贝


    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (mContext == null) {
            mContext = parent.getContext();
        }
        View view = LayoutInflater.from(mContext).inflate(R.layout.todo_item, parent, false);
        final ViewHolder holder = new ViewHolder(view);



        //在这里添加点击事件

        //文本被点击
        holder.textView.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                int position = holder.getAdapterPosition();
                String msg = mtodoList.get(position).content;

                //显示底部对话框并传值过去
                FragmentManager fm = ((MainActivity)mContext).getSupportFragmentManager();
                InputBottom editNameDialog = new InputBottom();
                Bundle bundle = new Bundle();
                bundle.putString("msg", msg);//信息
                bundle.putInt("position", position);//位置
                editNameDialog.setArguments(bundle);
                editNameDialog.show(fm, "bottom_dialog");
            }
        });

        //被长按
        holder.textView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                final int position = holder.getAdapterPosition();
                PopupMenu popupMenu=new PopupMenu(mContext,v);//1.实例化PopupMenu
                ((Activity)mContext).getMenuInflater().inflate(R.menu.todo_item,popupMenu.getMenu());//2.加载Menu资源
                //3.为弹出菜单设置点击监听
                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){

                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()){
                            case R.id.context_option_delete:
                                TodoAdapter.this.delete(position);
                                return true;
                            case R.id.context_option_deleteAll:
                                TodoAdapter.this.deleteAll();
                                return true;
                            case R.id.context_option_remain: //添加提醒按钮被点击
                                Intent intent = new Intent(mContext, RemainClock.class);
                                intent.putExtra("title", mtodoList.get(position).content);
                                mContext.startActivity(intent);
                            default:
                                return false;
                        }
                    }
                });
                popupMenu.show();//4.显示弹出菜单
                return true;
            }
        });

        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
        String str = mtodoList.get(position).content;
        holder.textView.setText(str);

        int status = mtodoList.get(position).status;
        if(status == 1){
            holder.checkBox.setImageResource(R.mipmap.checkbox_choose);
            holder.delete_line.setVisibility(View.VISIBLE);
        }else{
            holder.checkBox.setImageResource(R.mipmap.checkbox);
            holder.delete_line.setVisibility(View.GONE);
        }
//        holder.setIsRecyclable(false);
        holder.checkBox.setOnClickListener(null);
        //复选框
        holder.checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mtodoList.get(holder.getAdapterPosition()).status == 0){//刚开始没选中
                    changePosition(holder.getAdapterPosition(), true);
                    holder.delete_line.setVisibility(View.VISIBLE);
                    holder.checkBox.setImageResource(R.mipmap.checkbox_choose);
                }else{//从选中到不选中
                    changePosition(holder.getAdapterPosition(), false);
                    holder.delete_line.setVisibility(View.GONE);
                    holder.checkBox.setImageResource(R.mipmap.checkbox);
                }
            }
        });

    }

    @Override
    public int getItemCount() {
        return mtodoList.size();
    }


    static class ViewHolder extends RecyclerView.ViewHolder{
        CardView cardView;
        ImageView checkBox;
        TextView textView;
        View delete_line;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            cardView = itemView.findViewById(R.id.cardview);
            checkBox = itemView.findViewById(R.id.todo_CheckBox);
            textView = itemView.findViewById(R.id.todo_text);
            delete_line = itemView.findViewById(R.id.delete_line);
        }
    }




    /**
     * @param position 修改的位置
     * @param flag true position变为已完成   false position变为未完成
     * @return boolean  true修改成功  修改失败
     */
    protected boolean changePosition(int position, boolean flag){
        if(flag){
            swap(position, MainActivity.cnt, true);
            mtodoList.get(MainActivity.cnt).status = 1;

            notifyItemMoved(position, MainActivity.cnt);//from->to
            MainActivity.cnt--;//未完成列g表数减1

            if(!MainActivity.sfinish){//如果不展示完成列表，需要把此完成记录从列表中删除
                MainActivity.allList.add(mtodoList.get(MainActivity.cnt+1));
                mtodoList.remove(MainActivity.cnt+1);
                notifyItemRemoved(MainActivity.cnt+1);
            }
        }else{
            swap(position, 0, false);
            mtodoList.get(MainActivity.cnt+1).status = 0;

            notifyItemMoved(position, 0);
            MainActivity.cnt++;
        }

//        Log.d("20182005085", "changePosition: "+MainActivity.cnt);

        return true;
    }

    /**
     * 在mtodoList中交换位置1和位置2
    * @param p1 旧位置
     * @param p2 新位置
     */
    protected void swap(int p1, int p2, boolean flag){
        if(flag){
            String s = mtodoList.get(p1).content;
            for(int i=p1;i<p2;i++){
                mtodoList.get(i).content = mtodoList.get(i+1).content;
            }

            mtodoList.get(p2).content = s;
        }else{
            String s = mtodoList.get(p1).content;
            for(int i=p1;i>=1;i--){
                mtodoList.get(i).content = mtodoList.get(i-1).content;
            }
            mtodoList.get(0).content = s;
        }

    }


    /**
     * 删除list中的位置position
     * @param pos 删除的位置
     */
    protected void delete(int pos){
        if(mtodoList.get(pos).status == 0){
            MainActivity.cnt--;
        }
        mtodoList.remove(pos);
        notifyItemRemoved(pos);
//        notifyItemRangeChanged(pos, mtodoList.size()-1);
//        Log.d("20182005085", "delete: "+MainActivity.cnt);
    }

    protected void deleteAll(){
        int len = mtodoList.size();
        for(int i=len-1;i>=0;i--){
            delete(i);
        }
    }

}
